//
//  LocationTool.m
//  AiShangJinFuSalesman
//
//  Created by AiShangTong on 2017/6/8.
//  Copyright © 2018年 AiShangTong. All rights reserved.
//

#import "LocationTool.h"

@interface LocationTool ()<CLLocationManagerDelegate>

@property (strong, nonatomic)CLLocationManager *locationManager;   //
@property (strong, nonatomic)CLGeocoder *geocoder;

@end

@implementation LocationTool

+(instancetype)defaultLocation {
    static LocationTool *locationTool;
    static dispatch_once_t onceToken;
    dispatch_once(&onceToken, ^{
        locationTool = [[LocationTool alloc] init];
    });
    return locationTool;
}

- (void)startLocation {
    
    [self.locationManager startUpdatingLocation];
    
}

- (CLLocationManager *)locationManager {
    
    if (!_locationManager) {
        
        _locationManager = [[CLLocationManager alloc] init];
        //取得用户授权   不管应用是否在前台运行，都可以获取用户授权；
        [_locationManager requestWhenInUseAuthorization];
        //定位服务，每隔多少米定位一次；
        _locationManager.distanceFilter = 10;
        //定位的精确度，越高越耗电
        _locationManager.desiredAccuracy = kCLLocationAccuracyBest;
        //指定代理
        _locationManager.delegate = self;
        _locationManager.pausesLocationUpdatesAutomatically = YES; //该模式是抵抗ios在后台杀死程序设置，iOS会根据当前手机使用状况会自动关闭某些应用程序的后台刷新，该语句申明不能够被暂停，但是不一定iOS系统在性能不佳的情况下强制结束应用刷新
        _geocoder = [[CLGeocoder alloc] init];
    }
    return _locationManager;
}

#pragma mark -------地图代理方法--------

//实时获取的定位信息    代理方法会被多次执行
- (void)locationManager:(CLLocationManager *)manager didUpdateLocations:(NSArray<CLLocation *> *)locations {
    
    if (locations.count) {
        //获取最新位置
        CLLocation *location = locations.lastObject;
        [JPUSHService setLocation:location];
        if ([self.LocationDelegate respondsToSelector:@selector(locationToolCoordinatec:)]) {
            
            [self.LocationDelegate locationToolCoordinatec:location.coordinate];
        }
        //    NSLog(@"经度：%f,纬度：%f,海拔：%f,航向：%f,行走速度：%f", location.coordinate.longitude, location.coordinate.latitude,location.altitude,location.course,location.speed);
        
        [_geocoder reverseGeocodeLocation:location completionHandler:^(NSArray<CLPlacemark *> * _Nullable placemarks, NSError * _Nullable error) {
            if (placemarks.count > 0) {
                CLPlacemark *placemark = [placemarks objectAtIndex:0];
                
                //获取城市
                NSString *city = placemark.locality;
                if (!city) {
                    //四大直辖市的城市信息无法通过locality获得，只能通过获取省份的方法来获得（如果city为空，则可知为直辖市）
                    city = placemark.administrativeArea;
                }
                                
                if ([self.LocationDelegate respondsToSelector:@selector(locationToolPlacemark:)]) {
                    
                    if (placemark.addressDictionary[@"FormattedAddressLines"][0]) {
                        [self.LocationDelegate locationToolPlacemark:[NSString stringWithFormat:@"%@",placemark.addressDictionary[@"FormattedAddressLines"][0]]];
                    }else {
                        [self.LocationDelegate locationToolPlacemark:[NSString stringWithFormat:@"%@%@%@%@%@%@%@",placemark.country,placemark.administrativeArea,city,placemark.subLocality,placemark.subThoroughfare,placemark.thoroughfare,placemark.name]];
                    }
                    
                }
                
                
            }else if (error == nil && [placemarks count] == 0) {
                NSLog(@"No results were returned.");
            } else if (error != nil){
                NSLog(@"An error occurred = %@", error);
            }
        }];

        [self.locationManager stopUpdatingLocation];
    }
}

//定位失败
- (void)locationManager:(CLLocationManager *)manager didFailWithError:(NSError *)error{
    
    if ([error code] == kCLErrorDenied) {
        
        NSLog(@"定位被拒绝");
        NSURL *url = [NSURL URLWithString:UIApplicationOpenSettingsURLString];
        [HUD_Mao showCharacterMessage:@"需打开定位权限"];
        if ([[UIApplication sharedApplication] canOpenURL:url]) {
            [[UIApplication sharedApplication] openURL:url];
            
        }
    }
    if ([error code] == kCLErrorLocationUnknown) {
        
        NSLog(@"定位失败 = %@", error);
    }
}


@end
